# coding:utf-8
class Node(object):
    """节点"""
    def __init__(self,elem):
        self.elem = elem
        self.next = None

class SingleLinkList(object):
    """单链表"""  
    def __init__(self,node = None):
        if(node == None):
            self.next = None      # 前面加'__'的变量是私有变量,不能被外部修改
        else:
            self.next = Node(node)
        
    def is_empty(self) ->bool:
        # if(self.next): return False
        # return True
        return self.next == None
    
    def length(self)->int:
        pnode = self
        num = 0
        while pnode.next:
            num += 1
            pnode = pnode.next
        return num

    def append(self,item):
        """尾插法"""
        node = Node(item)
        pnode = self
        while(pnode.next != None):   # 找到末尾
            pnode = pnode.next
        pnode.next = node

    def add(self,item):
        """头插法"""
        node = Node(item)
        node.next = self.next
        self.next = node

    def insert(self,pos,item):
        """
         param: pos 要添加节点的位置,在此之前,插入item节点
                pos 从0开始 如果pos位置超过了链表范围，则在最后位置插入
        """
        node = Node(item)
        pnode = self
        while pos and pnode.next:
            pnode = pnode.next
            pos -= 1
        node.next = pnode.next
        pnode.next = node

    def search(self,item):
        """
        寻找链表中有没有相同的元素
        """
        pnode = self
        while pnode.next :
            if pnode.next.elem == item:
                return True
            pnode = pnode.next
        return False

    def remove(self,pos):
        """ 
        pos : 位置 ，0代表第一个节点，-1最后一个节点
        返回被删除的节点的元素

        """
        pnode = self
        while pos and pnode.next.next:
            pnode = pnode.next
            pos -= 1
        back = pnode.next
        pnode.next = pnode.next.next
        return back.elem

    def travel(self):
        cur = self.next
        while(cur != None):
            print(cur.elem)
            cur = cur.next

if __name__ == "__main__":
    l = SingleLinkList()
    l.append(100)
    l.append(1.2)
    l.append('3')
    l.travel()
    print("---\r\nremove:",end='')
    node = l.remove(-1)
    if node :
        print(node)
    else: print("节点为空")

    l.travel()
    print("end")



